﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using BlazorOrdering.Core;
using BlazorOrdering.Application;
using Microsoft.AspNetCore.Components;
using BlazorOrdering.Web.Entry.Areas.Identity.Data;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using BootstrapBlazor.Components;

namespace BlazorOrdering.Web.Entry.Pages
{
    public partial class Unsubscribe
    {
        private Message MessageElement { get; set; }
        [Inject]
        public MessageService MessageService { get; set; }
        [Inject] public UserManager<BlazorOrderingUser> UserManager { get; set; }
        [Inject] public AuthenticationStateProvider AuthenticationStateProvider { get; set; }

        [Inject]
        public IOrderService orderService { get; set; }

        private List<Order>? orders { get; set; }

        private string userCustomName { get; set; }

        protected override async Task OnInitializedAsync()
        {
            base.OnInitialized();
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;
            if (user.Identity.IsAuthenticated)
            {
                //下单人
                userCustomName = UserManager.GetUserAsync(user).Result.CustomName;
            }
            orders = await orderService.GetOnesCanCancelOrdersAsync(userCustomName);// 获得可以退订的订单列表
        }

        //protected async Task<Task> OnRowButtonClick(BoMenu menu)
        protected async Task<Task> OnRowButtonClick(Order order)
        {
            string result = await  orderService.CancelOrdersAsync(order);
            if (result=="ok")
            {
                ShowMessage("退订成功");
                //表格的行要删除
                orders.Remove(order);
                StateHasChanged();
            }
            else
            {
                ShowMessage(result);
            }
            return Task.CompletedTask;
        }

        private void ShowMessage(string msg)
        {
            MessageElement.SetPlacement(Placement.Top);
            MessageService?.Show(new MessageOption()
            {
                Host = MessageElement,
                Content = msg
            });
        }

    }
}
